package other.system.client.sap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.system.client.apitool.SAPClientUtils;
import other.system.client.util.HCDateUtils;
import other.system.client.util.HCXObjectService;
import other.system.client.util.ResultBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 同步SAP客户数据_SAP客户编码
 * @Author 黎炎松
 * 2024-08-12 09:58
 */
public class SyncSapAccount implements ScheduleJob, FutureTask {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static XoqlService xoqlService = XoqlService.instance();

    private static final Logger logger = LoggerFactory.getLogger();
    private static final String LOGGER_MSG = "同步客户SAP客户编码 ==> ";

    /**
     * 计划作业
     * @param scheduleJobParam
     */
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        try {
            logger.info(LOGGER_MSG + "触发计划作业");
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    /**
     * 异步任务
     * @param s
     * @throws ScriptBusinessException
     */
    @Override
    public void execute(String s) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + "执行异步任务");
        syncAccountSapCode();
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        new SyncSapAccount().syncAccountSapCode();

        //Account account = new Account();
        //account.setId(3453456348748361L);
        //account = hcxObjectService.get(account);
        //new SyncSapAccount().syncAccountSapCodeByAccount(account);
    }

    /**
     * 新增客户同步sap编码
     */
    public void syncAccountSapCodeByAccount(Account account) {
        try {
            logger.info("新增客户查询客户编码");
            String accountName = account.getAccountName();

            JSONObject params = new JSONObject();
            params.put("I_JKLX", "N");
            params.put("I_NAME", accountName);
            logger.info("params:" + params);

            ResultBody resultBody = SAPClientUtils.sendPost(params, SAPClientUtils.GET_ACCOUNT_URL, "");
            logger.info("resultBody:" + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.error("获取SAP客户编码数据异常:" + resultBody.getMessage());
                return;
            }

            JSONObject result = (JSONObject) resultBody.getResult();
            List<JSONObject> accountList = JSONArray.parseArray(result.getString("IT_KHXX"), JSONObject.class);
            logger.info("accountList: " + accountList.size());
            if (accountList.size() <= 0) {
                logger.debug("暂无需要处理的客户数据");
                return;
            }

            Account upAccount = new Account();
            upAccount.setId(account.getId());
            upAccount.setSapCustomerCode__c(accountList.get(0).getString("KUNNR"));
            logger.info("upAccount:" + upAccount);
            hcxObjectService.update(upAccount);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 同步客户sap编码
     */
    public void syncAccountSapCode() {
        try {
            logger.info(LOGGER_MSG + "处理开始");

            // 从数据配置表中获取上次更新时间
            String sql = "select id,lastSyncTime__c from syncConfig__c where syncKey__c = 'SAP_ACCOUNT_DATA'";
            SyncConfig__c syncConfig = hcxObjectService.queryOne(sql, SyncConfig__c.class);
            if (syncConfig == null) {
                logger.debug(LOGGER_MSG + "配置信息不存在");
                return;
            }

            // 获取同步时间
            String startDate = syncConfig.getLastSyncTime__c();
            String endDate = HCDateUtils.dateToString(new Date(), "yyyyMMdd"); // 同步结束时间
            if (StringUtils.isBlank(startDate)) {
                // 如果为空则退回1天前
                startDate = HCDateUtils.getDaysBeforeString(1, "yyyyMMdd");
            }

            JSONObject params = new JSONObject();
            params.put("I_JKLX", "N");
            //params.put("I_NAME", "墨奇科技（北京）有限公司"); // 客户名称（支持道号分割多个入参,中文道号分割）
            params.put("I_BTIME", startDate); // 开始日期 YYYYMMDD
            params.put("I_ETIME", endDate); // 结束日期
            logger.debug(LOGGER_MSG + "params:" + params);

            ResultBody resultBody = SAPClientUtils.sendPost(params, SAPClientUtils.GET_ACCOUNT_URL, "");
            logger.debug(LOGGER_MSG + "resultBody:" + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.error(LOGGER_MSG + "获取SAP客户编码数据异常:" + resultBody.getMessage());
                return;
            }

            JSONObject result = (JSONObject) resultBody.getResult();
            List<JSONObject> accountList = JSONArray.parseArray(result.getString("IT_KHXX"), JSONObject.class);
            logger.info(LOGGER_MSG + "accountList: " + accountList.size());
            if (accountList.size() <= 0) {
                logger.debug(LOGGER_MSG + "暂无需要处理的客户数据");
                // 更新同步配置
                syncConfig.setLastSyncTime__c(endDate);
                syncConfig.setLastSyncCount__c(0L);
                hcxObjectService.update(syncConfig);
                return;
            }

            // 根据客户名称获取系统中的客户数据
            String names = accountList.stream().map(v -> "'"+ v.getString("NAME").trim() +"'").collect(Collectors.joining(","));
            sql = "select id,accountName from account where accountName in (" + names + ")";
            List<JSONObject> crmAccountList = xoqlService.query(sql, true).getRecords();
            Map<String, Long> crmAccountMap = crmAccountList.stream().collect(Collectors.toMap(e -> e.getString("accountName"), e1 -> e1.getLong("id"), (e, e1) -> e));
            logger.info(LOGGER_MSG + "crmAccountMap: " + crmAccountMap.size());

            // 获取修改的数据
            List<Account> upAccountList = new ArrayList<>();
            for (JSONObject sapAccount : accountList) {

                String accountName = sapAccount.getString("NAME").trim();
                if (crmAccountMap.containsKey(accountName)) {
                    Account account = new Account();
                    account.setId(crmAccountMap.get(accountName));
                    account.setSapCustomerCode__c(sapAccount.getString("KUNNR"));
                    upAccountList.add(account);
                }

                if (upAccountList.size() > 100) {
                    Boolean update = hcxObjectService.batchUpdate(upAccountList);
                    logger.info(LOGGER_MSG + "修改客户SAP客户编码: " + update);
                    upAccountList.clear();
                }
            }

            // 批量修改
            if (upAccountList.size() > 0) {
                logger.debug(LOGGER_MSG + "修改的数据: " + upAccountList.size());
                Boolean update = hcxObjectService.batchUpdate(upAccountList);
                if (!update) {
                    logger.error(LOGGER_MSG + "批量修改异常");
                    //return;
                }
            }

            // 更新同步配置
            syncConfig.setLastSyncTime__c(endDate);
            syncConfig.setLastSyncCount__c(Long.valueOf(crmAccountMap.size()));
            Boolean update = hcxObjectService.update(syncConfig);
            if (!update) {
                logger.error(LOGGER_MSG + "更新同步配置异常");
                return;
            }

            logger.info(LOGGER_MSG + "处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(LOGGER_MSG + "同步异常: " + e.getMessage());
        }
    }



}
